package service

import (
	"shopping/dao/mysql"
	"shopping/errno"
	"shopping/model"
	"shopping/utils/hash"
	"shopping/utils/snowflake"
	"time"
)

type UserService struct {
	userDao *mysql.UserDao
}

// NewUserService 实例化NewUserService
func NewUserService(userDao *mysql.UserDao) *UserService {
	return &UserService{
		userDao: userDao,
	}
}

// Create 创建用户
func (service *UserService) Create(user *model.User) error {
	if user.Password != user.Password2 {
		return errno.ErrMismatchedPasswords
	}
	// 校验用户名是否存在
	_, err := service.userDao.GetByName(user.Username)
	if err == nil {
		return errno.ErrUserExistWithName
	}
	// 校验用户名是否有效
	if model.ValidateUserName(user.Username) {
		return errno.ErrInvalidUsername
	}
	// 校验密码是否有效
	if model.ValidatePassword(user.Password) {
		return errno.ErrInvalidPassword
	}
	// 创建用户
	user.Id = snowflake.GenID()
	user.CreateTime = time.Now()
	err = service.userDao.Create(user)
	return err
}

// GetUser 查询用户
func (service *UserService) GetUser(username string, password string) (model.User, error) {
	user, err := service.userDao.GetByName(username)
	if err != nil {
		return model.User{}, err
	}
	match := hash.CheckPasswordHash(password+user.Salt, user.Password)
	if !match {
		return model.User{}, errno.ErrUserNotFound
	}
	return user, nil
}

// UpdateUser 更新用户
func (service *UserService) UpdateUser(user *model.User) error {
	return service.userDao.Update(user)
}
